package model

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/tal-tech/go-zero/core/stores/sqlc"
	"github.com/tal-tech/go-zero/core/stores/sqlx"
	"github.com/tal-tech/go-zero/core/stringx"
	"github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
)

var (
	procInstFieldNames          = builderx.RawFieldNames(&ProcInst{})
	procInstRows                = strings.Join(procInstFieldNames, ",")
	procInstRowsExpectAutoSet   = strings.Join(stringx.Remove(procInstFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
	procInstRowsWithPlaceHolder = strings.Join(stringx.Remove(procInstFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
)

type (
	ProcInstModel interface {
		Insert(data ProcInst, tx ...sqlx.Session) (sql.Result, error)
		FindOne(id int64) (*ProcInst, error)
		Update(data ProcInst, tx ...sqlx.Session) error
		Delete(id int64, tx ...sqlx.Session) error
		IncCurrentNodeCompletedTaskCount(id int64, tx ...sqlx.Session) error
		// FindCanNext 查询查询流转到下一节点条件的流程实例
		FindCanNext(limit int) ([]*ProcInst, error)
	}

	defaultProcInstModel struct {
		conn  sqlx.SqlConn
		table string
	}

	ProcInst struct {
		Id                            int64     `db:"id"`
		ProcDefId                     int64     `db:"proc_def_id"`
		UserId                        string    `db:"user_id"`
		Key                           string    `db:"key"`
		Group                         string    `db:"group"`
		Title                         string    `db:"title"`
		MaxStep                       int64     `db:"max_step"`                          // 执行流最大下标（长度-1）
		CurrentStep                   int64     `db:"current_step"`                      // 当前执行到什么位置了
		CurrentNodeTaskCount          int64     `db:"current_node_task_count"`           // 当前节点的任务数
		CurrentNodeCompletedTaskCount int64     `db:"current_node_completed_task_count"` // 当前节点的完成任务数
		Status                        int64     `db:"status"`                            // 实例状态 0 = 关闭，1=开启
		CreateTime                    time.Time `db:"create_time"`
		UpdateTime                    time.Time `db:"update_time"`
	}
)

func NewProcInstModel(conn sqlx.SqlConn) ProcInstModel {
	return &defaultProcInstModel{
		conn:  conn,
		table: "`proc_inst`",
	}
}

func (m *defaultProcInstModel) Insert(data ProcInst, tx ...sqlx.Session) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", m.table, procInstRowsExpectAutoSet)
	ret, err := m.conn.Exec(query, data.ProcDefId, data.UserId, data.Key, data.Group, data.Title, data.MaxStep, data.CurrentStep, data.CurrentNodeTaskCount, data.CurrentNodeCompletedTaskCount, data.Status)
	return ret, err
}

func (m *defaultProcInstModel) FindOne(id int64) (*ProcInst, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", procInstRows, m.table)
	var resp ProcInst
	err := m.conn.QueryRow(&resp, query, id)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultProcInstModel) Update(data ProcInst, tx ...sqlx.Session) error {
	query := fmt.Sprintf("update %s set %s where `id` = ? and `update_time` <= ?", m.table, procInstRowsWithPlaceHolder)
	var err error
	if tx != nil && len(tx) > 0 && tx[0] != nil {
		_, err = tx[0].Exec(query, data.ProcDefId, data.UserId, data.Key, data.Group, data.Title, data.MaxStep, data.CurrentStep, data.CurrentNodeTaskCount, data.CurrentNodeCompletedTaskCount, data.Status, data.Id, data.UpdateTime)
	} else {
		_, err = m.conn.Exec(query, data.ProcDefId, data.UserId, data.Key, data.Group, data.Title, data.MaxStep, data.CurrentStep, data.CurrentNodeTaskCount, data.CurrentNodeCompletedTaskCount, data.Status, data.Id, data.UpdateTime)
	}
	return err
}

func (m *defaultProcInstModel) Delete(id int64, tx ...sqlx.Session) error {
	query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
	_, err := m.conn.Exec(query, id)
	return err
}

func (m *defaultProcInstModel) IncCurrentNodeCompletedTaskCount(id int64, tx ...sqlx.Session) error {
	query := fmt.Sprintf("update %s set `current_node_completed_task_count`=`current_node_completed_task_count`+1 where `id` = ?", m.table)
	var err error
	if tx != nil && len(tx) > 0 && tx[0] != nil {
		_, err = tx[0].Exec(query, id)
	} else {
		_, err = m.conn.Exec(query, id)
	}
	return err
}

func (m *defaultProcInstModel) FindCanNext(limit int) ([]*ProcInst, error) {
	query := fmt.Sprintf("select %s from %s where `current_node_task_count` == `CurrentNodeCompletedTaskCount` and `current_node_task_count` > 0 limit ?", procInstRows, m.table)
	resp := make([]*ProcInst, 0)
	if err := m.conn.QueryRows(&resp, query, limit); err != nil {
		return nil, err
	}
	return resp, nil
}
